package AdminService

import (
	"context"
	"database/sql"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gconv"
	"seawolf-admin-go/internal/request/BaseReq"
	"seawolf-admin-go/utility/db"
	"seawolf-admin-go/utility/response"
	"seawolf-admin-go/utility/tools"
	"strings"
	"time"
)

func Permmenu(ctx context.Context, req *BaseReq.I) *response.JsonResponse {
	if req.AdminId < 1 {
		return response.FailByRequestMessage(nil, "登录信息错误")
	}
	cacheAdminId := gconv.String(req.AdminId)
	cacheDurationTmp, err := g.Cfg().Get(ctx, "site.AdminCacheTimeout", 0)
	cacheDuration := cacheDurationTmp.Duration() * time.Second
	obj := db.GetUnSafaTable(ctx, "admin").Handler(db.SoftDeleteHandler).Where(
		"id",
		req.AdminId,
	)
	res, err := obj.Cache(gdb.CacheOption{
		Name:     "adminCache:" + cacheAdminId + ":model",
		Duration: cacheDuration,
	}).One()
	if err != nil {
		if err != sql.ErrNoRows {
			// 非 结果为空
			return response.FailByRequestMessage(nil, err.Error())
		}
	}
	if res.IsEmpty() {
		return response.FailByRequestMessage(nil, "获取信息失败")
	}
	result := res.Map()
	// 取部门
	resCon, err := db.GetUnSafaTable(ctx, "sys_department").Handler(db.SoftDeleteHandler).Where(
		"id",
		result["dept_id"],
	).Fields("name").Cache(gdb.CacheOption{
		Name:     "adminCache:" + cacheAdminId + ":depaName",
		Duration: cacheDuration,
	}).Value()
	result["departmentName"] = resCon.String()

	fanhui := g.Map{}
	// 取出 权限
	var permsRes []gdb.Value
	// 如果是 amdin ，取出全部
	if result["account"] == "admin" {
		permsRes, err = db.GetUnSafaTable(ctx, "sys_menu").Handler(db.SoftDeleteHandler).Where(
			"type = 2").Fields("perms").Array()
		if err != nil {
			return response.FailByRequestMessage(nil, err.Error())
		}
		// 取菜单
		resMenu, err := db.GetUnSafaTable(ctx, "sys_menu").Handler(db.SoftDeleteHandler).Where("type<2").
			Order("type asc,sort desc, id asc").All()
		if err != nil {
			return response.FailByRequestMessage(nil, err.Error())
		}
		fanhui["menus"] = resMenu.List()
	} else {
		dbPrefix, err := g.Cfg().Get(ctx, "database.prefix", "")
		permsRes, err = db.GetUnSafaTable(ctx, "sys_menu").As("sm").LeftJoin("sys_role_menu srm",
			"srm.menu_id = sm.id").Where(
			"sm.delete_at<1 AND sm.type = 2 AND srm.role_id IN (SELECT role_id FROM "+dbPrefix.String()+
				"admin_role WHERE admin_id = ?)",
			req.AdminId).Fields("sm.perms").Cache(gdb.CacheOption{
			Name:     "adminCache:" + cacheAdminId + ":perms",
			Duration: cacheDuration,
		}).Array()
		if err != nil {
			return response.FailByRequestMessage(nil, err.Error())
		}
		// 取菜单
		resMenu, err := db.GetUnSafaTable(ctx, "sys_menu").As("sm").LeftJoin("sys_role_menu srm",
			"srm.menu_id = sm.id").Fields("DISTINCT sm.*").Where(
			"sm.delete_at<1 AND srm.role_id IN (SELECT role_id FROM "+dbPrefix.String()+"admin_role WHERE admin_id = ?)",
			req.AdminId).Cache(gdb.CacheOption{
			Name:     "adminCache:" + cacheAdminId + ":menu",
			Duration: cacheDuration,
		}).Order("type asc,sort desc, id asc").All()
		if err != nil {
			return response.FailByRequestMessage(nil, err.Error())
		}
		fanhui["menus"] = resMenu.List()
	}
	// 整理权限列表
	permsTmp := gconv.SliceStr(permsRes)
	var perms []string
	for _, item := range permsTmp {
		if strings.Index(item, ",") > -1 {
			perms = append(perms, strings.Split(item, ",")...)
		} else {
			perms = append(perms, item)
		}
	}
	perms = tools.RemoveDuplicatesAndEmpty(perms)
	if len(perms) > 0 {
		fanhui["perms"] = perms
	} else {
		fanhui["perms"] = []string{}
	}
	return response.SuccessByRequestMessageData(nil, "成功", fanhui)
}
